import type { Ability, WSHook } from '@vtuber/ThreeSDK';
import type { SdkInitData } from '../types/vtuber';

export default () => {
  // 传入的整体播报内容
  let value: string = '';
  let wsHook: WSHook | void;

  // 类型谓词判断engine是否初始化过
  const isEngine = (engineParam: Ability | void): engineParam is Ability => {
    return !!engineParam;
  };
  const isWsHook = (wsHookParam: WSHook | void): wsHookParam is WSHook => {
    return !!wsHookParam;
  };
  // 播放初始化
  const playInit = (
    valueParam: string,
    engine: Ability | void,
    sdkInitData: SdkInitData
  ): Promise<WSHook> => {
    if (!isEngine(engine)) {
      return;
    }
    return new Promise((resolve) => {
      engine.addWSCallback((wsHookParams: WSHook) => {
        resolve(wsHookParams);
      });
      engine.sendWSText(valueParam, sdkInitData.userId, { speed: sdkInitData.speed || 1 });
    });
  };

  // 调节音量
  const adjustVolume = (volume: number, engine: Ability | void) => {
    if (!isEngine(engine)) {
      return;
    }
    engine.setVolume(volume);
  };

  return {
    value,
    playInit,
    wsHook,
    isWsHook,
    adjustVolume
  };
};
